<template>
  <div
    class="app-container"
    v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-col :span="12">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="虚拟馆名称" prop="libName">
              <el-input v-model="form.libName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="端口" prop="libDomains.0">
              <el-input v-model="form.libDomains[0]"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址" prop="libDomains.1">
              <el-input v-model="form.libDomains[1]"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="虚拟馆图片" prop="logoUrl">
              <FileUpload
                v-model="form.logoUrl"
                :fileType="['png', 'jpg', 'jpeg']"
                :url="url"
                @input="getFirelist"
                @deleteFile="deleteFile"
                @giveMediaType="giveMediaType"
                ref="fileUpload"
                :dynamicHeaders="dynamicHeaders"
                :dynamicMethod="dynamicMethod"
                :dynamicUrl="dynamicUrl"
                :ossId="ossId"
                :limit="1"
                :drag="true"
                :listType="'picture'"
              ></FileUpload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="虚拟馆描述" prop="description">
              <editorCom
                ref="editorCom"
                :value="form.description"
                @input="handleInput"
              ></editorCom>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item>
              <el-button type="primary" @click="onSubmit">保存</el-button>
              <el-button @click="onCancel">取消</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-col>
    </el-form>
  </div>
</template>

<script>
import FileUpload from "@/components/FileUpload";
import editorCom from "@/components/Editor";
import { getVirlib, editVirlib } from "@/api/pavilion.js";
import { postOssUpload } from "@/api/oss";
export default {
  name: "",
  components: {
    FileUpload,
    editorCom,
  },
  data() {
    return {
      form: {
        libName: "",
        libDomains: [],
        logoUrl: [],
        logoOid: "",
        description: "",
      },
      rules: {
        libName: [
          { required: true, message: "虚拟馆名称不能为空", trigger: "blur" },
        ],
        "libDomains.0": [
          { required: true, message: "端口不能为空", trigger: "blur" },
        ],
        "libDomains.1": [
          { required: true, message: "地址不能为空", trigger: "blur" },
        ],
      },
      loading: true,
      uploadParams: {
        path: "pavilion-picture",
        name: "虚拟馆图片",
        permission: "tenant",
        suffix: "",
        mediaType: "",
        sizeLimit: "",
        attachment: "",
      },
      url: "",
      ossId: "",
      dynamicHeaders: {},
      dynamicMethod: "PUT",
      dynamicUrl: null,
      imageOidList: [],
    };
  },
  mounted() {
    this.requestVirlib();
  },
  methods: {
    requestVirlib() {
      this.loading = true;
      getVirlib()
        .then((res) => {
          console.log(res);
          this.loading = false;
          if (res.success) {
            let logoUrl = res?.data?.logoUrl ?? "";
            this.$set(this.form, "libName", res?.data?.libName ?? "");
            this.$set(this.form, "libDomains", res?.data?.libDomains ?? []);
            this.$set(this.form, "logoUrl", [logoUrl]);
            this.$set(this.form, "logoOid", res?.data?.logoOid ?? "");
            this.$set(this.form, "description", res?.data?.description ?? "");
          }
        })
        .catch((err) => {
          this.loading = false;
          console.log(err);
        });
    },
    getFirelist(data) {
      data.forEach((item) => {
        // imageOidList不包含该ossId则push
        if (item.ossId && !this.imageOidList.includes(item.ossId)) {
          this.imageOidList.push(item.ossId);
        }
      });
      this.dynamicHeaders = {};
      this.dynamicMethod = "PUT";
      this.dynamicUrl = null;
      this.ossId = "";
      // console.log(this.form, this.imageOidList, "imageOidList");
    },
    deleteFile(file) {
      // 找到form.file中对应的对象，删除
      let index = this.form.logoUrl.findIndex((item) => {
        if (typeof item === "object" && Object.keys(item).length > 0) {
          return item.url === file.url;
        } else {
          return item === file.url;
        }
      });
      if (index !== -1) {
        // 找到imageOidList中对应的对象，删除
        this.form.logoUrl.splice(index, 1);
        this.imageOidList.splice(index, 1);
      }
      // console.log(this.form);
      // console.log(this.imageOidList);
    },
    giveMediaType(mediaType) {
      this.uploadParams.mediaType = mediaType;
      this.uploadParams.suffix = this.uploadParams.mediaType.match(/\/(.+)/)[1]
      this.requestpostOssUpload();
    },
    requestpostOssUpload() {
      postOssUpload(this.uploadParams)
        .then((res) => {
          if (res.success) {
            this.dynamicHeaders = res.data.headers || {};
            this.dynamicMethod = res.data.method || "PUT";
            this.dynamicUrl = res.data.uploadUrl || "";
            this.ossId = res?.data?.ossId ?? null;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleInput(val) {
      this.form.description = val;
    },
    onSubmit() {
      let popDealArr = [
        "save",
        "确定保存并更新虚拟馆的基础信息?",
        "已取消保存",
      ];
      this.popDeal(popDealArr);
    },
    onCancel() {
      let popDealArr = [
        "cancel",
        "确定取消当前的编辑恢复到上一次保存的状态?",
        "已取消",
      ];
      this.popDeal(popDealArr);
    },
    popDeal(popDealArr) {
      const text = popDealArr[1];
      this.$confirm(text, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (popDealArr[0] === "save") {
            this.requestSave();
          } else {
            this.cancel();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: popDealArr[2],
          });
        });
    },
    requestSave() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let prams = {
            libName: this.form.libName,
            libDomains: this.form.libDomains,
            logoOid: this.imageOidList[0],
            description: this.form.description,
          };
          editVirlib(prams)
            .then((res) => {
              if (res.success) {
                this.$message.success("保存成功");
                this.requestVirlib();
              } else {
                this.$message.error("保存失败");
              }
            })
            .catch((err) => {
              this.$message.error("保存失败");
            });
        }
      });
    },
    cancel() {},
  },
};
</script>

<style lang="scss" scoped>
</style>
